package org.jeecg.modules.demo.zkfish.envdata.controller;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.crypto.hash.Hash;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.demo.zkfish.fishfeedback.entity.FishFeedback;
import org.jeecg.modules.demo.zkfish.fishfeedback.service.IFishFeedbackService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/zkfish.envdata/envdatainfo")
@Slf4j
public class EnvDataInfoController {


    @Value("${datainfo.envdir}")
    private String envBasePath;

    @Value("${datainfo.downloaddir}")
    private String downloaddir;

    List<Object> headNaneArray = new ArrayList<>();
    HashMap<String,String> headMap = new HashMap<>();
    List<List<Object>> datas = new ArrayList<>();

    String curExcelDate = null;

    public EnvDataInfoController(){
        headMap.put("chl","叶绿素(mg/m³)");
        headMap.put("o2","溶解氧(mg/m³)");
        headMap.put("so","盐度(mg/m³)");
        headMap.put("thetao","海温(℃)");
        headMap.put("uo","北向流速(m/s)");
        headMap.put("vo","东向流速(m/s)");
        headMap.put("mld","混合层厚度(m)");
        headMap.put("ssha","海面异常高度(m)");
    }

    @GetMapping(value = "/get")
    public Result<Map<String, HashMap<String,Object>>> queryPageList(double lon,double lat,String date) throws Exception {
        Result<Map<String, HashMap<String,Object>>> result = new Result<>();
        HashMap<String,HashMap<String,Object>> v1 = getDataFromExcel(lon,lat,date);
        result.setResult(v1);
        result.setMessage("操作成功");
        return result;
    }

    public  HashMap<String,HashMap<String,Object>> getDataFromExcel(double lon,double lat,String date) throws Exception {
        buildWorkbook(date);
        int rowIndex = getIndexFromLonlat(lon,lat);
        HashMap<String,HashMap<String,Object>> v1 = buildRowMap(getRowCSV(rowIndex,datas),headNaneArray);
        System.out.println(v1);
        return v1;
    }

    public static void downloadFile(String fileURL, String savePath) {
        File saveDir = new File(savePath.substring(0, savePath.lastIndexOf("/")));
        if (!saveDir.exists()) {
            if (!saveDir.mkdirs()) {
                throw new RuntimeException("创建目录失败: " + saveDir.getAbsolutePath());
            }
        }

        try {
            URL url = new URL(fileURL);

            try (InputStream inputStream = url.openStream();
                 FileOutputStream outputStream = new FileOutputStream(savePath)) {

                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                System.out.println("文件下载成功 " + savePath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static List<List<Object>> readCSVFile(String csvFilePath) {
        List<List<Object>> allRows = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(csvFilePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 假设CSV文件使用逗号作为分隔符，并且没有引号或转义字符
                String[] values = line.split(",");
                List<Object> row = Arrays.asList(values);
                allRows.add(row); // 注意：这里使用的是Arrays.asList返回的固定大小列表
                // 如果你需要一个可以修改的列表，使用 new ArrayList<>(Arrays.asList(values))
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return allRows;
    }

    public void buildWorkbook(String date) throws Exception {
        if(!date.equals(curExcelDate)){
            System.out.println("新的env日期，开始创建workbook对象"+date);
            curExcelDate = date;
            SimpleDateFormat sp = new SimpleDateFormat("yyyy-M-d");
            Date dateObj = sp.parse(date);
            SimpleDateFormat sf = new SimpleDateFormat("yyyy/M/d");
            String dateDir = sf.format(dateObj);
            String remoteExcelPath = envBasePath + dateDir + "/env.csv";
            String localExcelPath = downloaddir  + dateDir + "/env.csv";

            File excelDir = new File(downloaddir + dateDir);
            if(!excelDir.exists() || !excelDir.isDirectory()){
                excelDir.mkdirs();
            }

            downloadFile(remoteExcelPath,localExcelPath);

            datas = readCSVFile(localExcelPath);
            headNaneArray = getRowCSV(0,datas);
        }
    }

    public int getIndexFromLonlat(double lon, double lat){
        if(lon > 0 && lon < 159||
                lon < 0 && lon >-81||
                lat > 0.1 || lat < -41){
            throw new RuntimeException("坐标:"+lon+","+lat+"不合法");
        }
        if(lon < 0){
            lon = 180 + lon + 180;
        }
        int lonIndex = (int)((lon - 160)/0.25);
        int latIndex = (int)((0 - lat)/0.25);
        System.out.println(lon+","+lat+",的行索引是"+(latIndex * 481 + lonIndex));
        return latIndex * 481 + lonIndex;
    }

    public HashMap<String,HashMap<String,Object>> buildRowMap(List<Object> datas,List<Object> headNaneArray){
        HashMap<String, HashMap<String,Object>> valueMap = new HashMap<>();
        for (int i = 0; i <datas.size(); i++) {
            String headName = headNaneArray.get(i).toString();
            if(headName.indexOf("mult")>=0){
                continue;
            }
            if(headName.indexOf("Vms")>=0){
                continue;
            }
            String name = "";
            String depth = "";
            if(headName.indexOf("_")>0){
                String[] nameinfo = headName.split("_");
                name = nameinfo[0];
                depth = nameinfo[1];
            }
            else{
                name = headName;
                depth = "0";
            }
            name = headMap.get(name);
            if (valueMap.get(name) == null) {
                valueMap.put(name,new HashMap<>());
            }
            try{
                BigDecimal value = new BigDecimal(datas.get(i).toString());
                BigDecimal roundedValue = value.setScale(2, RoundingMode.HALF_UP);
                valueMap.get(name).put(depth,roundedValue.doubleValue());
            }
            catch (Exception e){
                valueMap.get(name).put(depth,"/");
                log.error("获取环境数据出错",e);
            }

        }
        valueMap.get("混合层厚度(m)").put("50","/");
        valueMap.get("混合层厚度(m)").put("100","/");
        valueMap.get("混合层厚度(m)").put("150","/");
        valueMap.get("混合层厚度(m)").put("200","/");
        valueMap.get("混合层厚度(m)").put("300","/");
        valueMap.get("海面异常高度(m)").put("50","/");
        valueMap.get("海面异常高度(m)").put("100","/");
        valueMap.get("海面异常高度(m)").put("150","/");
        valueMap.get("海面异常高度(m)").put("200","/");
        valueMap.get("海面异常高度(m)").put("300","/");
        return valueMap;
    }

    public List<Object> getRowCSV(int rowIndex, List<List<Object>> sheet){
        List<Object> values = new ArrayList<>();
        if (sheet.get(rowIndex) != null) {
            System.out.println("打印第"+rowIndex+"行");
            values = sheet.get(rowIndex);
        } else {
            throw new RuntimeException(rowIndex+"行数不合法");
        }
        return values;
    }
}
